package P120_NotUseStopToThread;

/**
 * @ClassName : NotUseStopToThread
 * @Description : 不使用stop方法停止线程
 * @Author : wukj1
 * @Date: 2022/5/6
 **/
public class NotUseStopToThread {

    public static void main(String[] args) throws InterruptedException {
//        Thread thread =new Thread(){
//            @Override
//            public void run() {
//                try{
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    //异常处理
//                }
//                System.out.println("此代码不会执行");
//            }
//        };
//        thread.start();
//        Thread.sleep(100);
//        //子线程停止
//        thread.stop();

//        MultiThread t = new MultiThread();
//        Thread t1 = new Thread(t);
//        t1.start();
//        for (int i = 0; i < 5; i++) {
//            new Thread(t).start();
//        }
//        t1.stop();

        SafeStopThread t = new SafeStopThread();
        t.start();
        Thread.sleep(10);
        t.terminate();

    }

}

class MultiThread implements Runnable {
    private int a = 0;

    private volatile boolean stop = false;

    @Override
    public void run() {
        //同步代码块，保证原子操作
        synchronized ("") {
            a++;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            a--;
            String tn = Thread.currentThread().getName();
            System.out.println(tn + ":a = " + a);
        }
    }
}

class SafeStopThread extends Thread{
    private int a = 0;

    private volatile boolean stop = false;

    @Override
    public void run() {
       while(!stop){
           //同步代码块，保证原子操作
           synchronized ("") {
               a++;
               try {
                   Thread.sleep(100);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               a--;
               String tn = Thread.currentThread().getName();
               System.out.println(tn + ":a = " + a);
           }
       }
    }

    public void terminate(){
        stop = true;
    }
}
